<?php

namespace App\Providers;

use App\Util\AppUtil;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

class RecordSqlServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {

    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        if (config('logging.channel_sql_status')
            && (!AppUtil::isCli() || config('logging.channel_sql_record_when_cli'))
        ) {
            DB::listen(function (QueryExecuted $query) {
                $sql = str_replace(['%', '?'], ['%%', '%s'], $query->sql);
                $bindings = array_map(function ($value) {
                    return is_numeric($value) ? $value : "'{$value}'";
                }, $query->bindings);

                if ($query->time > 500) {
                    Log::channel('sql_json')->alert(vsprintf($sql, $bindings), ['time' => sprintf("%.2f", $query->time)]);
                }
                else {
                    Log::channel('sql_json')->info(vsprintf($sql, $bindings), ['time' => sprintf("%.2f", $query->time)]);
                }
            });
        }
    }
}
